package com.caojin.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.caojin.propertyInjector.locationResolver.ClassPathLocationResolver;

/**
 * properties文件工具类
 * @author caojin
 */
public abstract class PropertiesUtil {

	private static String filePath = ClassPathLocationResolver.DEFAULT_BASE_PACKAGE
			+ File.separator + ClassPathLocationResolver.DEFAULT_FILE_NAME;

	/**
	 * 加载配置文件
	 * 
	 * @param filePath
	 *            classpth下的文件位置
	 * @return
	 */
	public static Properties loadProperties(String filePath) {

		@SuppressWarnings("serial")
		class FileLoadFaidException extends RuntimeException {
			public FileLoadFaidException(String msg) {
				super(msg);
			}

			public FileLoadFaidException(Throwable e) {
				super(e);
			}
		}

		Properties props = new Properties();
		InputStream in = PropertiesUtil.class.getResourceAsStream(filePath);
		if (in == null) {
			throw new FileLoadFaidException("file not exists: " + filePath);
		}
		try {
			props.load(in);
		} catch (IOException e) {
			throw new FileLoadFaidException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return props;
	}

	/**
	 * 加载property文件
	 * 
	 * @param in
	 * @return
	 */
	public static Properties loadProperties(InputStream in) {
		Properties props = new Properties();
		try {
			props.load(in);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return props;
	}

	public static Properties loadPropeties() {
		return loadProperties(filePath);
	}

	public static void setFilePath(String filePath) {
		PropertiesUtil.filePath = filePath;
	}

	public static String getProperty(String property) {
		Properties props = loadProperties(filePath);
		return props.getProperty(property);
	}
}
